import store from '@/store'
import $cookies from '@/utils/cookies.js'
import $http from '@/utils/request'
import moment from 'moment'
/**
 * 权限
 * @param {*} key
 */
export function hasPermission (key) {
  return window.SITE_CONFIG['permissions'].indexOf(key) !== -1 || false
}

/**
 * 获取字典label
 * @param key
 * @param val
 * @returns {string}
 */
export function getDictLabel (key, val) {
  let data = getDictList(key)
  if (data && data.length >= 0) {
    let vals = data.filter(item => item.val === val + '')
    if (vals && vals.length > 0) {
      return vals[0].label
    } else {
      return ''
    }
  }
}

/**
 * 获取指定key的字典集合
 * key dict_type
 * valid true 有效项目
 */
export function getDictList (key, valid) {
  const dictData = window.SITE_CONFIG['dictData']
  let keyData = {}
  if (dictData && dictData.length >= 0) {
    keyData = dictData.filter(item => item.key === key)[0]
  }
  if (keyData && keyData.val) {
    let arr = []
    // 使用方面获取有效数组
    if (valid) {
      arr = keyData.val.filter(item => item.status.toString() !== '0')
    } else {
      arr = keyData.val
    }
    return arr
  } else {
    return []
  }
}

/**
 * 获取指定key的字典树形集合
 * key dict_type
 * valid true 有效项目
 */
export function getDictTreeList (key, valid) {
  const dictData = window.SITE_CONFIG['dictData']
  let keyData = {}
  if (dictData && dictData.length >= 0) {
    keyData = dictData.filter(item => item.key === key)[0]
  }
  if (keyData && keyData.val) {
    let arr = []
    // 使用方面获取有效数组
    if (valid) {
      arr = keyData.val.filter(item => item.status.toString() !== '0')
    } else {
      arr = keyData.val
    }
    arr = JSON.parse(JSON.stringify(arr))
    arr = treeDataTranslate(arr)
    return arr
  } else {
    return []
  }
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  store.commit('resetStore')
  $cookies.remove('token')
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = false
}

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 获取svg图标(id)列表
 */
export function getIconList () {
  var res = []
  let list = document.querySelectorAll('svg symbol')
  if (list) {
    for (const item of list) {
      res.push(item.id)
    }
    // list.forEach(item => {
    //   res.push(item.id)
    // })
  }
  return res
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'pid') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (!temp[data[k][pid]] || data[k][id] === data[k][pid]) {
      res.push(data[k])
      continue
    }
    if (!temp[data[k][pid]]['children']) {
      temp[data[k][pid]]['children'] = []
    }
    temp[data[k][pid]]['children'].push(data[k])
    data[k]['_level'] = (temp[data[k][pid]]._level || 0) + 1
  }
  return res
}

/**
 *  yyyy-MM-dd HH:mm:ss 截取为 yyyy-MM-dd
 * @param dateTimeStr
 * @returns {string}
 */
export function getDateStr (dateTimeStr) {
  return dateTimeStr.substr(0, 10)
}

/**
 * 读取数据行
 * @param {*} data 集合
 * @param {*} val 值
 * @param {*} fieldName 字段名 默认 val
 * @return 文本
 */
export function getDataItem (data, value, fieldName = 'val') {
  let keyData = data.filter(item => (item[fieldName] || '').toString() === (value || '').toString())[0]
  if (keyData) {
    return keyData
  }
  return {}
}

/**
 * 格式化输出日期
 * @param {*} d 日期时间
 * @param {*} format 格式默认YYYY-MM-DD HH:mm:ss
 */
export function formatDate (d, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!d) return null
  return moment(d).format(format)
}
export function getToken () {
  return $cookies.get('token')
}
export function setToken (token) {
  let c = {}
  if (store.state.modulesModel && store.state.cookieDomain) {
    c = { domain: store.state.cookieDomain }
  }
  $cookies.set('token', token, c)
}
/**
 * 获取带token的url
 * @param {*} url
 */
export function getTokenUrl (url) {
  if (!url) return null
  return url + `?token=${getToken()}`
}

/**
 * 获取带token的url
 * @param {*} url
 */
export function downloadFile (url) {
  if (!url) return null
  // 删除项目前缀
  url = url.replace(window.SITE_CONFIG['apiURL'], '')
  $http.get(`${url}`, { responseType: 'blob' }).then(({ data: res, headers }) => {
    const link = document.createElement('a')
    // , { type: 'application/vnd.ms-excel' }
    let blob = new Blob([res])
    // 获取heads中的filename文件名
    let temp = headers['content-disposition'].split(';')[1].split('filename=')[1]
    let iconv = require('iconv-lite')
    iconv.skipDecodeWarning = true// 忽略警告
    let fileName = decodeURI(iconv.decode(temp, 'gbk'))
    // return
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }).catch(() => { })
  return url + `?token=${getToken()}`
}
